package org.threads.threadpool;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.threads.threadpool.task.Task;

/**
 * Model of ProcessingThread, which obtains tasks from queue
 * and processes it.
 *
 * @author oler
 */
public class ProcessingThread implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProcessingThread.class);

    /**
     * Queue with waiting tasks to be processed.
     */
    private final TasksQueue processQueue;

    /**
     * Common constructor.
     *
     * @param processQueue   queue with tasks
     * @throws IllegalArgumentException if queue is <code>null</code>
     */
    public ProcessingThread(final TasksQueue processQueue)
            throws IllegalArgumentException {

        if (processQueue == null) {
            throw new IllegalArgumentException("Queue object cannot be equal to null!");
        }

        this.processQueue = processQueue;
    }

    /**
     * Entry point for custom thread.
     */
    @Override
    public void run() {

        while (true) {

            Task process = null;

            synchronized (processQueue) {

                if (processQueue.isEmpty()) {
                    continue;
                }

                process = processQueue.getProcess();
            }

            try {

                LOGGER.info(Thread.currentThread().getName() + ":  "
                        + "START processing task [ " + process.getId() + " ]");

                process.performTask();

                LOGGER.info(Thread.currentThread().getName() + ":  "
                        + "END processing task [ " + process.getId() + " ]");

            } catch (InterruptedException ex) {
                LOGGER.error(ex.toString());
            }

        }

    }
}
